package net.weitalk.asm;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import static org.objectweb.asm.Opcodes.ACC_PUBLIC;

public class CustomClassWriter {
    final static Logger logger = Logger.getLogger(CustomClassWriter.class.getName());
    static String CLASSNAME = "java.lang.Integer";
    static String cloneableInterface = "java/lang/Cloneable";
    
    ClassReader reader;
    ClassWriter writer;
    
    AddFieldAdapter addFieldAdapter;
    PublicizeMethodAdapter publicizeMethodAdapter;

    public CustomClassWriter() {
        try {
            reader = new ClassReader(CLASSNAME);
            writer = new ClassWriter(reader, 0);
        } catch (IOException e) {
            logger.log(Level.SEVERE, null, e);
        }
    }
    
    public CustomClassWriter(byte[] contents) {
        reader = new ClassReader(contents);
        writer = new ClassWriter(reader, 0);
    }
    
    public byte[] addField() {
        addFieldAdapter = new AddFieldAdapter(
                "aNewBooleanField",
                ACC_PUBLIC,
                writer
        );
        reader.accept(addFieldAdapter, 0);
        logger.info("aNewBooleanField is added.");
        return writer.toByteArray();
    }
    
    public byte[] publicizeMethod() {
        publicizeMethodAdapter = new PublicizeMethodAdapter(writer);
        reader.accept(publicizeMethodAdapter, 0);
        return writer.toByteArray();
    }
}
